<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../StaticFiles/element-plus-2.9.1/index.css" rel="stylesheet">
  <link href="../StaticFiles/nprogress/nprogress.min.css" rel="stylesheet">
  <link href="../styles/vue-page-common.css" rel="stylesheet">
  <script src="../Scripts/pollyfills/Array.prototype.flat.js"></script>
  <script src="../Scripts/pollyfills/ResizeObserver.js"></script>
  <script src="../StaticFiles/vue3/vue.global.prod.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/index.full.min.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/icons-vue.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/zh-cn.min.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <title>热表转工排产维护</title>
  <style>
    .el-table--large .cell {
      padding: 0 10px !important;
    }
  </style>
</head>

<body>
  <div id="app" v-cloak>
    <!-- 报表表头 -->
    <vue3-report-header :title="'热表转工排产维护'"></vue3-report-header>
    <div style="padding: 10px;" @keyup.enter="getData">
      <!-- 查询条件区 -->
      <el-form :inline="true" :model="dataObj.queryInfo" ref="queryInfoRef" :label-position="'left'"
        :disabled="!dataObj.formEnabled">
        <el-form-item label="承制分厂:">
          <el-input v-model="dataObj.queryInfo.specfactoryname" disabled></el-input>
        </el-form-item>

        <el-form-item label="主制分厂:">
          <el-select style="width: 160px;" v-model="dataObj.queryInfo.factoryname" placeholder="请选择主制分厂" clearable
            filterable>
            <el-option v-for="f in dataObj.factoryList" :key="f.factoryname" :label="f.factoryname"
              :value="f.factoryname">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="零件图号:">
          <el-autocomplete v-model.trim="dataObj.queryInfo.productname" placeholder="请输入零件图号" :trigger-on-focus="false"
            style="width:240px;" :fetch-suggestions="searchProductAsync" :value-key="'productname'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item prop='containername' label="流水卡号:">
          <el-autocomplete v-model.trim="dataObj.queryInfo.containername" placeholder="请输入流水卡号"
            :trigger-on-focus="false" style="width:280px;" :fetch-suggestions="searchContainerAsync"
            :value-key="'containername'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="维护状态:">
          <el-select v-model="dataObj.queryInfo.status" placeholder="请选择" style="width: 120px;" clearable>
            <el-option :key="'未维护'" :label="'未维护'" :value="'未维护'"></el-option>
            <el-option :key="'已维护'" :label="'已维护'" :value="'已维护'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="锁定状态:">
          <el-select v-model="dataObj.queryInfo.lockstatus" placeholder="请选择" style="width: 100px;" clearable>
            <el-option :key="'已锁定'" :label="'已锁定'" :value="'已锁定'"></el-option>
            <el-option :key="'未锁定'" :label="'未锁定'" :value="'未锁定'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否开卡:">
          <el-select v-model="dataObj.queryInfo.isstart" placeholder="请选择" style="width: 100px;" clearable>
            <el-option :key="'已开卡'" :label="'已开卡'" :value="'已开卡'"></el-option>
            <el-option :key="'未开卡'" :label="'未开卡'" :value="'未开卡'"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="计划发出时间:">
          <el-date-picker v-model="dataObj.queryInfo.plannedstartdate" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" :shortcuts="dataObj.shortcuts">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="计划完成时间:">
          <el-date-picker v-model="dataObj.queryInfo.plannedfinishdate" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" :shortcuts="dataObj.shortcuts">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="'Search'" size="default" @click="getData">查询</el-button>
          <el-button type="success" :icon="'CircleCheckFilled'" size="default" :disabled="!dataObj.saveEnabled"
            v-if="dataObj.saveEnabled" @click="multipleSave">批量保存
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="dataObj.dataList" stripe border show-overflow-tooltip v-loading.fullscreen.lock="dataObj.loading"
        :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)"
        @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="40" v-if="!dataObj.unlockEnabled"></el-table-column>
        <el-table-column prop="factoryname" label="主制分厂" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="isstart" label="是否开卡" width="80" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.isstart === '未开卡' ? 'danger' : 'success'">{{scope.row.isstart}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productdescription" label="零件名称" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="containername" label="流水卡号" show-overflow-tooltip sortable></el-table-column>
        <el-table-column prop="qty" label="数量" width="60"></el-table-column>
        <el-table-column prop="workflowstepname" label="工序" width="120" show-overflow-tooltip sortable>
        </el-table-column>
        <el-table-column prop="rbplaner" label="热表排产人" width="90" show-overflow-tooltip></el-table-column>
        <el-table-column prop="stepplanshipdate" label="热表排产时间" width="100" :formatter="splitDate"></el-table-column>
        <el-table-column prop="status" label="维护状态" width="90" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.status === '已维护' ? 'success' : 'danger'">{{scope.row.status}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isshiplocked" label="已锁定" width="75" show-overflow-tooltip>
          <template #default="scope">
            <el-switch v-model="scope.row.isshiplocked" @change="changeShipLocked(scope.row)" active-text="是"
              inactive-text="否" inline-prompt :disabled="!dataObj.unlockEnabled">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="plannedstartdate" label="计划发出时间" width="130" sortable :formatter="splitDate">
        </el-table-column>
        <el-table-column prop="plannedfinishdate" label="计划完成时间" width="160">
          <template #default="scope">
            <el-date-picker v-if="!scope.row.isshiplocked && dataObj.saveEnabled" ref="ref" type="date"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 135px;" v-model="scope.row.plannedfinishdate">
            </el-date-picker>
            <span v-else>
              {{ scope.row.plannedfinishdate !== null ? scope.row.plannedfinishdate.split('T')[0] : '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" v-if="dataObj.saveEnabled">
          <template #default="scope">
            <el-button type="success" :disabled="!dataObj.saveEnabled" :icon="'CircleCheckFilled'" size="small"
              @click="saveSingleRowData(scope.row)">保 存
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="jijiaplaner" label="机加排产人" width="90" show-overflow-tooltip></el-table-column>
        <el-table-column prop="stepplancreatedate" label="机加排产时间" width="100" :formatter="splitDate"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :disabled="!dataObj.formEnabled" :current-page="dataObj.currentPage" :page-sizes="[dataObj.pageSize,20,50,100]"
        :page-size="dataObj.pageSize" layout="prev,pager,next,jumper,sizes,total" :total="dataObj.total">
      </el-pagination>

      <!-- 回到顶部 -->
      <el-backtop></el-backtop>
    </div>
  </div>
  <script type="module">
    import { getFactory, fetchSuggestion, getParams } from '../Scripts/hooks/useCommonMethod.js'
    import { prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth } from '../Scripts/hooks/vue3DateShortCut.js'
    import { splitDate } from '../Scripts/hooks/format.js'
    const { createApp, reactive, ref, onMounted, watch } = Vue
    const { ElMessage, ElMessageBox, ElNotification } = ElementPlus
    import Vue3ReportHeader from '../Scripts/components/Vue3ReportHeader.js';
    const App = {
      setup() {
        const dataObj = reactive({
          loading: false,
          loadingText: '数据加载中...',
          currentPage: 1,// 当前页
          pageSize: 12, // 每页显示条数
          total: 0,
          queryInfo: {
            productname: '',
            containername: '',
            plannedstartdate: '',
            plannedfinishdate: '',
            status: '',
            lockstatus: '',
            isstart: '',
            specfactoryname: '',
            specfactoryid: ''
          },
          dataList: [],
          factoryList: [],
          userInfo: {},
          formEnabled: true,
          saveEnabled: true, //是否允许修改
          unlockEnabled: false, //是否允许解锁
          multipleSelection: [],
          shortcuts: [prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth]
        })

        // 查询用户信息
        async function getUserInfo(uid) {
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/RbContainerStepPlanMaint.ashx?actions=getUserInfo',
            method: 'post',
            data: { type: 'getUserInfo', uid }
          });
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (data.length == 0) {
            dataObj.formEnabled = false;
            return ElNotification({
              title: '错误',
              message: '用户不存在!',
              type: 'error',
              duration: 0
            })
          }
          dataObj.userInfo = { ...data[0] };
          dataObj.queryInfo.specfactoryname = data[0].factoryname;
          dataObj.queryInfo.specfactoryid = data[0].factoryid;
          const { rolename } = data[0];
          if (rolename.indexOf('计划重排') != -1) {
            // 计划重排角色不可以修改并保存计划完时间，但允许修改锁定状态
            dataObj.saveEnabled = false;
            dataObj.unlockEnabled = true;
            dataObj.queryInfo.status = '已维护';
          } else {
            dataObj.queryInfo.status = '未维护';
            if (rolename.indexOf('计划员') != -1 || rolename.indexOf('调度员') != -1) {
              // 计划员、调度员可以修改并保存计划完时间，但不能修改锁定状态
              dataObj.saveEnabled = true;
              dataObj.unlockEnabled = false;
            } else {
              dataObj.formEnabled = false;
              return ElNotification({
                title: '错误',
                message: '当前用户非计划员或调度员!',
                type: 'error',
                duration: 0
              })
            }
          }
        };

        // 查询数据
        async function getData() {
          dataObj.loading = true
          dataObj.loadingText = '数据加载中...'
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/RbContainerStepPlanMaint.ashx?actions=getData',
            method: 'post',
            data: {
              ...dataObj.queryInfo,
              currentPage: dataObj.currentPage,
              pageSize: dataObj.pageSize,
              type: 'getData'
            }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.dataList = data.map(item => {
            return { ...item, isshiplocked: item.isshiplocked === '已锁定' }; //将【锁定状态】由字符串变更为布尔值
          });
          dataObj.total = total;
        };

        // 保存一行数据
        async function saveSingleRowData(row) {
          const { plannedfinishdate, containerstepplanid, isshiplocked } = row;
          if (isshiplocked) {
            return ElMessage.error('已锁定不能修改，若想重排，请联系相关人员解锁后再试!');
          }
          if (!plannedfinishdate) {
            return ElMessage.error('计划完成时间不能为空!');
          }
          if (dayjs().isAfter(plannedfinishdate, 'day')) {
            return ElMessage.error('计划完成时间不能小于系统当前日期，请修改后再保存!');
          }
          dataObj.loading = true
          dataObj.loadingText = '数据加载中...'
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/RbContainerStepPlanMaint.ashx?actions=saveSingleRowData',
            method: 'post',
            data: {
              type: 'saveSingleRowData',
              plannedfinishdate,
              containerstepplanid,
              uid: dataObj.userInfo.employeeid
            }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (total > 0) {
            ElMessage.success('保存成功!');
            row.rbplaner = dataObj.userInfo.fullname;
            row.stepplanshipdate = dayjs().format('YYYY-MM-DD');
            row.isshiplocked = true;
          }
        };

        // 保存多行
        async function multipleSave() {
          const multipleSelectionData = dataObj.multipleSelection.filter(item => !item.isshiplocked);
          if (multipleSelectionData.length === 0) {
            return ElMessage.error('请至少选择1条未锁定的数据!');
          }
          const hasNullData = multipleSelectionData.some(item => !item.plannedfinishdate);
          if (hasNullData) {
            return ElMessage.error('存在要求完成时间为空的数据，不能批量保存!');
          }
          const hasBeforeData = multipleSelectionData.some(item => dayjs().isAfter(item.plannedfinishdate, 'day'));
          if (hasBeforeData) {
            return ElMessage.error('存在要求完成时间小于当前时间的数据，不能批量保存!');
          }
          dataObj.loading = true;
          dataObj.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/RbContainerStepPlanMaint.ashx?actions=multipleSave',
            method: 'post',
            data: {
              type: 'multipleSave',
              multipleSaveData: data,
              uid: dataObj.userInfo.employeeid
            }
          })
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (total > 0) {
            ElMessage.success('批量保存成功!');
            getData();
          }
        };

        // 切换锁定状态
        async function changeShipLocked(row) {
          const { containerstepplanid, isshiplocked } = row;
          // 切换锁定状态确认
          const confirmResult = await ElMessageBox.confirm('是否切换锁定状态?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)

          // 取消切换
          if (confirmResult !== 'confirm') {
            row.isshiplocked = !isshiplocked;
            return ElMessage.info('已取消切换!')
          }

          const { data: { data, meta, total } } = await axios.post('../handler/report/RbContainerStepPlanMaint.ashx?action=changeShipLocked', {
            type: 'changeShipLocked',
            containerstepplanid,
            isshiplocked: isshiplocked === true ? '1' : '0'
          });

          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (total > 0) {
            ElMessage.success('锁定状态切换成功');
          } else {
            ElMessage.error('锁定状态切换失败');
          }
        };

        // 处理行选择
        function handleSelectionChange(val) {
          dataObj.multipleSelection = val;
        };

        function handleCurrentChange(newPage) {
          dataObj.currentPage = newPage;
          getData();
        };

        function handleSizeChange(newSize) {
          dataObj.pageSize = newSize;
          getData();
        };

        function searchContainerAsync(value, callback) {
          fetchSuggestion({ actionName: 'getContainernameAsync', name: 'containername', value, callback })
        }

        function searchProductAsync(value, callback) {
          fetchSuggestion({ actionName: 'getProductnameAsync', name: 'productname', value, callback });
        }

        onMounted(() => {
          getFactory(dataObj);
          if (!getParams('uid')) {
            dataObj.formEnabled = false;
            return ElNotification({
              title: '错误',
              message: '缺少用户信息!',
              type: 'error',
              duration: 0
            })
          }
          getUserInfo(getParams('uid'));
        })

        watch(() => dataObj.queryInfo, () => { dataObj.currentPage = 1; }, { deep: true })

        return {
          dataObj,
          getData,
          saveSingleRowData,//保存一行数据
          multipleSave,//批量保存
          changeShipLocked,//切换锁定状态
          handleSelectionChange,
          handleCurrentChange,
          handleSizeChange,
          searchContainerAsync,//批次号
          searchProductAsync,//件号
          splitDate
        }
      }
    };

    const app = createApp(App);
    app.use(ElementPlus, {
      locale: ElementPlusLocaleZhCn,
      size: 'large'
    });
    // 注册所有icon
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component)
    }
    app.component('vue3-report-header', Vue3ReportHeader);
    app.mount('#app');
  </script>
</body>

</html>